{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "201\n",
      "{'user': {'id': 'JZ15732'}, 'token': {'expiry': 14400.0}, 'permissions': ['REFERRAL']}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "from os.path import expanduser\n",
    "from requests.auth import HTTPBasicAuth\n",
    "\n",
    "with open(expanduser('brain_credentials.txt')) as f:\n",
    "  credentials = json.load(f)\n",
    "\n",
    "username,password = credentials\n",
    "\n",
    "sess = requests.Session()\n",
    "\n",
    "sess.auth = HTTPBasicAuth(username,password)\n",
    "\n",
    "response = sess.post('https://api.worldquantbrain.com/authentication')\n",
    "\n",
    "print(response.status_code)\n",
    "print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "simulation_data = {\n",
    "    'type' : 'REGULAR',\n",
    "    'settings' : {\n",
    "        'instrumentType' : 'EQUITY',\n",
    "        'region' : 'USA',\n",
    "        'universe' : 'TOP3000',\n",
    "        'delay' : 1,\n",
    "        'decay' : 0,\n",
    "        'neutralization' : 'INDUSTRY',\n",
    "        'truncation' : 0.08,\n",
    "        'pasteurization': 'ON',\n",
    "        'unitHandling' : 'VERIFY',\n",
    "        'nanHandling': 'OFF',\n",
    "        'language' :'FASTEXPR',\n",
    "        'visualization':False,\n",
    "    },\n",
    "    'regular' : 'liabilities/assets'\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Z78omnj\n"
     ]
    }
   ],
   "source": [
    "from time import sleep\n",
    "sim_resp = sess.post(\n",
    "      'https://api.worldquantbrain.com/simulations',\n",
    "      json=simulation_data,\n",
    ")\n",
    "# print(sim_resp.headers)\n",
    "sim_progress_url = sim_resp.headers['Location']\n",
    "\n",
    "while True:\n",
    "      sim_progress_resp = sess.get(sim_progress_url)\n",
    "      retry_after_sec = float(sim_progress_resp.headers.get(\"Retry-After\",0))\n",
    "      if retry_after_sec == 0:\n",
    "                  break\n",
    "      sleep(retry_after_sec)\n",
    "alpha_id = sim_progress_resp.json()[\"alpha\"]\n",
    "print(alpha_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请求成功\n",
      "响应头: {'Date': 'Tue, 14 Jan 2025 14:48:12 GMT', 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': '0', 'Connection': 'keep-alive', 'Retry-After': '2.5', 'Location': 'https://api.worldquantbrain.com/simulations/3bnRuZ8UF4KK9gwFoaUtUaw', 'Allow': 'POST, OPTIONS', 'X-Request-Id': '3dce9a61e56049089ce21a3f99a2c8a6', 'X-Frame-Options': 'SAMEORIGIN', 'Vary': 'Accept-Language, Cookie, Origin', 'Content-Language': 'en', 'Access-Control-Allow-Origin': 'https://platform.worldquantbrain.com', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Expose-Headers': 'Location,Retry-After', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'}\n",
      "Location URL: https://api.worldquantbrain.com/simulations/3bnRuZ8UF4KK9gwFoaUtUaw\n",
      "模拟进度: {'progress': 0.1}\n"
     ]
    }
   ],
   "source": [
    "from time import sleep\n",
    "\n",
    "sim_resp = sess.post(\n",
    "    'https://api.worldquantbrain.com/simulations',\n",
    "    json=simulation_data,\n",
    ")\n",
    "\n",
    "# 检查状态码\n",
    "if sim_resp.status_code == 201:\n",
    "    print(\"请求成功\")\n",
    "else:\n",
    "    print(f\"请求失败，状态码：{sim_resp.status_code}\")\n",
    "\n",
    "# 检查响应头\n",
    "print(\"响应头:\", sim_resp.headers)\n",
    "\n",
    "# 获取 Location URL（不区分大小写）\n",
    "sim_progress_url = sim_resp.headers.get('location') or sim_resp.headers.get('Location')\n",
    "if sim_progress_url:\n",
    "    print(\"Location URL:\", sim_progress_url)\n",
    "else:\n",
    "    print(\"响应头中没有 Location 字段\")\n",
    "\n",
    "# 继续后续逻辑\n",
    "if sim_progress_url:\n",
    "    while True:\n",
    "        sim_progress_resp = sess.get(sim_progress_url)\n",
    "        if sim_progress_resp.status_code == 200:\n",
    "            print(\"模拟进度:\", sim_progress_resp.json())\n",
    "            break\n",
    "        sleep(1)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
